<?php		

/**
 * 
 * sys,robot,admin为保留账号，用户的id从100起
 * 
 */

class PassportAdmin extends AdminBase{


	private $nohf = array("login","dologin","reg","regmphone","doreg","dologout","regsuccess");
	private $adhf = array("index");

	private $api = null;
	private $conf = null;//;
	/**
	 * 构造函数，初始化插件
	 */
	public function __construct() {
		parent::__construct();
		/*
		if(!n_api("rbac")->check("passport-admin") && in_array(N_ACTION,array('index','setoff','seton')))
			throw new Exception("这是火星！地球人不允许进入");
		if(!n_api("rbac")->check("passport-conf") && in_array(N_ACTION,array('confedit','confsave')))
			throw new Exception("这是木星！地球人不允许进入");
		*/

		$this->api = n_api("passport");
		//将标准头加进来，在析构函数中加了标准尾。对于风格的变化，只需要调整标准头标准尾
		//api("user")->isLogin();
		// $this->conf = n_api("nconfig")->getSite('master',N_EVENT);
		//print_r($this->conf);
		//如果已经登陆了，但还进入注册、登陆页面，那么跳转到首页了
		if($this->api->islogin() && in_array(N_ACTION,array('login','loginmin','reg','regmphone','regmin','wapreg','waplogin'))){
			n_go("/user/index.html");
		}

		if(!in_array(N_ACTION,$this->nohf) && 'page'==N_TYPE){
			n_mod('skin')->header('admin-simple');
		}

	}

	public function index(){
		$rs = $param = $this->param("page:page,uname:char:ignore");
		$perpage = 20;
		$start = ($param['page']-1)*$perpage;
		$mysql = n_api("mysql")->cname('weixin');
		$wheresql = empty($param['uname'])?'':" and uname like '%{$param['uname']}%'";
		$rs['data'] = $mysql->select("select * from passport_main where id>0{$wheresql} order by id desc limit {$start},{$perpage}");
		$rs['paging'] = n_api("common")->paging(n_url('passport','index'),$param['page'],$mysql->count(),$perpage);
		$this->_html("index",$rs);
	}

	/**
	 * [getNsiteList 查看用户的站点列表]
	 * @return [type] [description]
	 */
	public function getNsiteList(){
		$param = $this->param('ppid:int');
		
		$nsite = n_api('nsite');
		
		$rs['list'] = $nsite->getList($param['ppid']);

		$this->_html("getNsiteList",$rs);
	}
	
	public function setoff(){

		$param = $this->param("ppid:uint");
		$mysql = n_api("mysql")->cname('weixin');
		$ppinfo = $this->api->get($param['ppid']);
		if(empty($ppinfo)){
			throw new PException("找不到账号");
		}
		$mysql->update("passport_main",array('state'=>'OFF'),"id={$param['ppid']}");
		$this->_html("setoff");
	}
	public function seton(){

		$param = $this->param("ppid:uint");
		$mysql = n_api("mysql")->cname('weixin');
		$ppinfo = $this->api->get($param['ppid']);
		if(empty($ppinfo)){
			throw new PException("找不到账号");
		}
		$mysql->update("passport_main",array('state'=>'ON'),"id={$param['ppid']}");
		$this->_html("seton");
		
	}
	
	/**
	 * 找回密码
	 */
	public function recovery(){}
	
	public function login(){

		
		// n_mod('skin')->header('simple');
		$rs['isVcode'] = isset($_SESSION['isVcode'])&&'Y'==$_SESSION['isVcode']?'Y':'N';
		$this->_html('loginAdmin',$rs);
		// n_mod('skin')->footer('simple');
	}
	public function loginMin(){
		$this->_html('loginMin');
		n_mod('skin')->footer();
	}
	
	public function skeyLogin(){
		$param = $this->param("skey:char,url:char:ignore");
		$mysql = n_api("mysql")->cname('weixin');
		$uinfo = $mysql->fetchFirst("select * from passport_main where skey='{$param['skey']}'");
		if(empty($uinfo)){
			throw new PException("错误的登陆码");
		}
		
		$this->api->dologin($uinfo['id']);
		if(!empty($param['url'])){
			n_go($param['url']);
		}else{
			n_go(n_url("welcome"));
		}
	}
	public function dologin(){
		
		$param = $this->param("uname:char,password:char,vcode:char:ignore");

		$mysql = n_api("mysql")->cname('weixin');
		$ytime = N_NOW - 24*60*60;
		$tryNum = $mysql->fetchFirst("select count(*) as total from passport_login_try where account='{$param['uname']}' and ctime>{$ytime}");

		try{
			$ppinfo = $this->api->getByUname($param['uname']);
			// if($tryNum['total']>$this->conf['passport-trylogin_lock']['value']){
			// 	throw new PException("账号尝试次数超过设定，账号已锁定");
			// }
			if (!in_array($ppinfo['usertype'], ['sadmin', 'admin']))
				throw new PException("非管理员账号",0);
			if(empty($ppinfo)){
				throw new PException("账号错误",1);
			}
			if($ppinfo['password']!==$param['password']){
				throw new PException("密码错误",2);
			}
			if('OFF'==$ppinfo['state']){
				throw new PException("账号停止使用",2);
			}
			if(isset($_SESSION['isVcode']) && 'Y'==$_SESSION['isVcode']){
				if(empty($param['vcode']) || strtolower($_SESSION['vcode'])!=strtolower($param['vcode'])){
					throw new PException("验证码错误".$param['vcode'].'=='.$_SESSION['vcode']);
					
				}
			}
			$this->api->dologin($ppinfo['id']);
			
			//如果出现验证码，那么在登陆成功后将不再显示验证码了
			if(isset($_SESSION['isVcode'])){
				unset($_SESSION['isVcode']);
			}
			$rs = n_state(TRUE, "登陆成功");
			if(!empty($_SESSION['referer'])){
				$rs['referer'] = $_SESSION['referer'];
			}
		}catch(PException $p){
			$data['account'] = $param['email'];
			$data['ip'] = ip2long(n_api("common")->getClientIp());
			$data['ctime'] = N_NOW;
			$data['ltype'] = 'EMAIL';
			$mysql->insert("passport_login_try",$data);

			$rs = n_state(FALSE,$p->getMessage());


			if($tryNum['total']>$this->conf['trylogin_vcode']){
				$_SESSION['isVcode'] = 'Y';
				$rs['vcode'] = 'Y';
			}


		}
		
		//header("location: ".n_url('index','index'));
		//exit;
		echo json_encode($rs);
		//$this->_html('dologin',$rs);
	}
	
	public function welcome(){
		$this->_html("welcome");
	}
	
	public function dologout(){
		$_SESSION = array();
		n_go('/');
		$this->_html("dologout");
	}



	/**
	 * 删除一个用户
	 */
	public function del(){
		//linruiyan@2012-8-1 加入权限
		if(!n_api("rbac")->accessCheck("passport_del")){
			throw new PException("你无权操作");
		}
		
		$param = $this->param("id:uint");
		
		$db = n_api("mysql")->cname('weixin');
		$ppInfo = n_api("passport")->get($param['id']);
		$log = json_decode($minfo['oplog'],true);
		//print_r($log);
		$log[] = "{$_SESSION['uname']}于".date("Y-m-d H:i:s")."删除了用户";
		$db->update("passport_main",array('isdel'=>'Y','log'=>json_encode($log)),"id={$param['id']}");
		//n_api("redis")->c001->hmDelete('passport::online',$param['id']); //linruiyan@2012-11-24 清空缓存
		
		
		$this->_html('del');
		
	}
	public function undel(){
		//linruiyan@2012-8-1 加入权限
		if(!n_api("rbac")->accessCheck("passport_del")){
			throw new PException("你无权操作");
		}
		
		$param = $this->param("id:uint");
		
		$db = n_api("mysql")->cname('weixin');
		$ppInfo = n_api("passport")->get($param['id']);
		$log = json_decode($minfo['oplog'],true);
		//print_r($log);
		$log[] = "{$_SESSION['uname']}于".date("Y-m-d H:i:s")."恢复了用户";
		$db->update("passport_main",array('isdel'=>'N','log'=>json_encode($log)),"id={$param['id']}");
		//n_api("redis")->c001->hmDelete('passport::online',$param['id']); //linruiyan@2012-11-24 清空缓存
		
		
		$this->_html('undel');
		
	}
	
	/**
	 * 邮箱注册入口，可以设置为不允许注册
	 */
	public function reg(){
		
		//print_r($this->conf);
		if('N'==$this->conf['isopen']){
			throw new PException("暂时关闭邮箱注册！");
		}
		if('N'==$this->conf['isopen_email'] && 'Y'==$this->conf['isopen_mphone']){
			n_go(n_url('passport','regMphone'));
		}
		n_mod("skin")->header("simple");
		$this->_html("reg",$this->conf);
		n_mod("skin")->footer("simple");
	}
	/**
	 * 手机注册入口，可以设置为不允许注册
	 */
	public function regMphone(){
		if('N'==$this->conf['isopen']){
			throw new PException("暂时关闭手机注册！");
		}
		if('N'==$this->conf['isopen_mphone'] && 'Y'==$this->conf['isopen_email']){
			n_go(n_url('passport','reg'));
		}
		n_mod("skin")->header("simple");
		$this->_html("regMphone",$this->conf);
		n_mod("skin")->footer("simple");
	}


	public function regMin(){
		$this->_html("regMin");
	}

	public function doreg(){
		$param = $this->param("uname:char,password:char,repassword:char,vcode:char,login:char:ignore");
		try{
			if(!preg_match("/^[a-z]*$/",$param['uname'])){
				throw new PException("账号只能a-z组合");
			}

			if(strlen($param['uname'])<6){
				throw new PException("账号长度必须大于6");
			}
			
			if($param['password']!=$param['repassword']){
				throw new PException("输入的两次密码不同！");
			}
			if(strtolower($param['vcode'])!=strtolower($_SESSION['vcode'])){
				throw new PException("验证码错误！");
			}
			if(strlen($param['password'])<6){
				throw new PException("密码长度不能少于6位");
			}
			
			$ip = n_api("common")->getClientIp();
			
			if($this->api->regNum($ip)>$this->conf['passport-maxreg']['value']){
				throw new PException("系统异常，注册失败");
			}
			
			
			$ppid = $this->api->add($param['uname'],$param['password'],$ip);
			$this->api->initAvartar($ppid);

			$rs = $this->api->get($ppid);
			$rs['skey'] = $this->api->getSkey($ppid);
			
			//如果没有提供登陆参数，那么登陆
			if(!isset($param['dologin']) || 'N'!=$param['dologin']){
				$this->api->dologin($ppid);
			}
			$_SESSION['vcode'] = rand(1,1000000);
			$rs = n_state(TRUE, "注册成功");
			$rs['ppid'] = $ppid;
		}catch(PException $p){
			$rs = n_state(FALSE, $p->getMessage());
		}
		echo json_encode($rs);
		exit;
		$this->_html("doreg",$rs);
		
	}

	public function regSuccess(){
		n_go(n_url('nsite','index1'));
		exit;
		$rs = $this->api->get($_SESSION['ppid']);
		$this->_html("regSuccess",$rs);
	}


	/**
	 * 用户查看自己的登陆历史
	 */
	public function getOnlineLog(){
		
		$rs = n_api("passport")->getOnlineLog($_SESSION['ppid']);
		$this->_html("getOnlineLog",$rs);
	}






	public function wapReg(){
		$this->_html("wapReg");
	}
	public function wapDoreg(){
		$param = $this->param("email:char,password:char,repassword:char,vcode:char");
		if($param['password']!=$param['repassword']){
			throw new PException("输入的两次密码不同！");
		}
		if(strtolower($param['vcode'])!=strtolower($_SESSION['vcode'])){
			throw new PException("验证码错误！");
		}
		if(strlen($param['password'])<6){
			throw new PException("密码长度不能少于6位");
		}
		$ppHandle = n_api("passport");
		$ppid = $ppHandle->add($param['email'],$param['password']);
		$rs = $ppHandle->get($ppid);
		$rs['skey'] = $ppHandle->getSkey($ppid);
		$this->_html("wapDoreg",$rs);
	}









	public function wapLogin(){
		
		$this->_html('wapLogin');
	}

	public function wapDologin(){
		$param = $this->param("skey:char");
		$ppid = n_api("mysql")->cname('weixin')->fetchFirst("select id from passport_main where skey='{$param['skey']}'");
		if(empty($ppid)){
			throw new PException("秘钥不存在！");
		}
		n_api('passport')->dologin($ppid['id']);
		$rs['loginUrl'] = '192.168.108.183'.n_url("passport","dologin",array("skey"=>$param['skey']));
		$this->_html('wapDologin',$rs);
	}
	
	/**
	 * wap端对出登陆
	 */
	public function wapDologout(){
		if (!empty($_SESSION['ppid'])){
			$mysql =  n_api('mysql')->cname('weixin');
			$ppid = $_SESSION['ppid'];
			
			if(empty($_SESSION['log_id'])){
				$plog = $mysql->fetchFirst("select * from passport_log where ppid={$ppid} order by id desc");
				$logid = $plog['id'];
			}else{
				$logid = $_SESSION['log_id'];
			}
			if(!empty($logid)){
				//sunjian@20121122 鐧诲嚭
				$mysql->update("passport_log",array("logout_time"=>time(),"istimeout"=>'N'),"id={$logid}");
	 			$mysql->update("passport_main",array("isonline"=>'N'),"id={$ppid}");
	 		}
		}

		$_SESSION = array();
 		//linruiyan@2012-7-30 鐩存帴璺宠浆鐧诲綍椤甸潰
		header("location: ".n_url('passport','login'));
		exit;
		$this->_html('logout');
		
	}



	public function confEdit(){
		
		//是否关闭注册isopen
		//是否支持手机注册isopenEmail
		//是否支持邮箱注册isopenMphone
		
		//无任何操作自动掉线时长timeout
		//是否允许一个账号多终端同时登陆isParallel
		//同一个IP一天最多注册账号数量maxReg
		//尝试N次登陆后出现验证码trytimes
		//
		$rs = $this->conf;
		
		$this->_html("confEdit",$rs);
	}
	public function confSave(){

		$param = $this->param("
							isopen:char:ignore,
							isopenEmail:char:ignore,
							isopenMphone:char:ignore,
							timeout:uint,
							isParallel:char:ignore,
							maxReg:uint,
							tryvcode:uint,
							trylock:uint
		");
		
		$cHandle = n_api("nconfig");
		$data['isopen'] = empty($param['isopen'])?'N':$param['isopen'];
		$data['isopen_email'] = empty($param['isopenEmail'])?'N':$param['isopenEmail'];
		$data['isopen_mphone'] = empty($param['isopenMphone'])?'N':$param['isopenMphone'];
		$data['timeout_logout'] = $param['timeout'];
		$data['isparallel'] = empty($param['isParallel'])?'N':$param['isParallel'];
		$data['maxreg'] = $param['maxReg'];
		$data['trylogin_vcode'] = $param['tryvcode'];
		$data['trylogin_lock'] = $param['trylock'];
		$cHandle->pluginsUpdate($data);
		//$this->_html("confSave");
		n_mod("skin")->save("保存成功！");
	}

	public function siteIndex(){
		$param = $this->param("scode:char,page:page");
		$rs['scode'] = $param['scode'];
		$perpage = 20;
		$start = ($param['page']-1)*$perpage;
		$mysql = n_api("mysql")->cname('weixin');
		
		$rs['data'] = $mysql->select("select * from passport_main where scode='{$param['scode']}' limit {$start},{$perpage}");
		$rs['paging'] = n_api("common")->paging(n_url("passport","siteIndex",array("scode"=>$param['scode'])),$param['page'],$mysql->count(),$perpage);
		$this->_html("siteIndex",$rs);
	}




	public function bindEmailEdit(){
		if(!$this->api->isLogin()){
			throw new PException("错误请求");
		}
		$mysql = n_api("mysql")->cname('weixin');
		$uinfo = $mysql->fetchFirst("select * from passport_bind where main_id='{$_SESSION['ppid']}'");
		$this->_html("bindEmailEdit",$uinfo);
	}
	public function bindEmailSave(){
		$param = $this->param("email:char");
		$mysql = n_api("mysql")->cname('weixin');
		$binfo = $mysql->fetchFirst("select * from passport_bind where main_id={$_SESSION['ppid']}");
		
		$ppid = $_SESSION['ppid'];
		if(empty($binfo)){
			$mysql->insert("passport_bind",array('main_id'=>$ppid,'email'=>$param['email'],'be_time'=>N_NOW));
		}else{
			$mysql->update("passport_bind",array('email'=>$param['email'],'be_time'=>N_NOW),"main_id={$ppid}");
		}
		n_mod("skin")->save("绑定成功");
	}
	public function unbindEmail(){
		$mysql = n_api("mysql")->cname('weixin');
		$binfo = $mysql->fetchFirst("select * from passport_bind where main_id={$_SESSION['ppid']}");
		
		$ppid = $_SESSION['ppid'];
		if(empty($binfo)){
			throw new PException("请求错误");
		}
		$mysql->update("passport_bind",array('email'=>'','be_time'=>0),"main_id={$ppid}");
		n_mod("skin")->save("解除绑定成功");
		
	}

	public function bindMphoneEdit(){
		if(!$this->api->isLogin()){
			throw new PException("错误请求");
		}
		$mysql = n_api("mysql")->cname('weixin');
		$uinfo = $mysql->fetchFirst("select * from passport_bind where main_id='{$_SESSION['ppid']}'");
		$this->_html("bindMphoneEdit",$uinfo);

	}
	public function bindMphoneSave(){
		$param = $this->param("mphone:char");
		$mysql = n_api("mysql")->cname('weixin');
		$binfo = $mysql->fetchFirst("select * from passport_bind where main_id={$_SESSION['ppid']}");
		
		$ppid = $_SESSION['ppid'];
		if(empty($binfo)){
			$mysql->insert("passport_bind",array('main_id'=>$ppid,'mphone'=>$param['mphone'],'bp_time'=>N_NOW));
		}else{
			$mysql->update("passport_bind",array('mphone'=>$param['mphone'],'bp_time'=>N_NOW),"main_id={$ppid}");
		}
		n_mod("skin")->save("绑定成功");

	}

	public function unbindMphone(){
		$mysql = n_api("mysql")->cname('weixin');
		$binfo = $mysql->fetchFirst("select * from passport_bind where main_id={$_SESSION['ppid']}");
		
		$ppid = $_SESSION['ppid'];
		if(empty($binfo)){
			throw new PException("请求错误");
		}
		$mysql->update("passport_bind",array('mphone'=>'','bp_time'=>0),"main_id={$ppid}");
		n_mod("skin")->save("解除绑定成功");

	}

	
	public function __destruct(){
		//加入标准尾。
		if(!in_array(N_ACTION,$this->nohf) && 'page'==N_TYPE){
			n_mod('skin')->footer('admin-simple');
		}
	}

		
}


